<template>
  <div class="wrapper">
    <el-card class="login-box">
      <el-form
        class="login-form"
        ref="loginFromRef"
        :rules="loginRules"
        :model="loginForm"
      >
        <div class="title-container">
          <h3 class="title">用 户 登 录</h3>
        </div>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            :prefix-icon="Lock"
            v-model="loginForm.password"
            placeholder="请输入用户密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
            class="block"
            :loading="loading"
            type="primary"
            @click="handleLogin"
            native-type="submit"
            >登 录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { User, Lock } from "@element-plus/icons";
import { validatePassword } from "./rules";

// 数据源
const loginForm = ref({
  username: "super-admin",
  password: "123456",
});

// 验证规则
const loginRules = ref({
  username: [
    {
      required: true,
      trigger: "blur",
      message: "请输入正确的用户名",
    },
  ],
  password: [
    {
      required: true,
      trigger: "blur",
      validator: validatePassword(),
    },
  ],
});

// 登录动作处理
const loading = ref(false);
const loginFromRef = ref(null);
const store = useStore();
const router = useRouter();
const handleLogin = () => {
  loginFromRef.value.validate((valid) => {
    if (!valid) return;

    loading.value = true;
    store
      .dispatch("user/login", loginForm.value)
      .then(() => {
        loading.value = false;
        // 登录后操作
        router.push("/");
      })
      .catch((err) => {
        console.log(err);
        loading.value = false;
      });
  });
};
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
$cursor: #fff;

.wrapper {
  position: relative;
  height: 100%;
  margin: 0;
  padding: 0;
  background-color: $bg;
  overflow: hidden;

  .login-box {
    position: absolute;
    top: 240px;
    left: 50%;
    width: 320px;
    margin-left: -160px;
    background-color: $bg;

    .login-form {
      .title-container {
        .title {
          font-size: 26px;
          color: $light_gray;
          margin-bottom: 40px;
          text-align: center;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
